package org.lewis.woman.service;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.commons.dbutils.DbUtils;
import org.lewis.common.domain.EmailTask;
import org.lewis.common.jdbc.QueryHelper;
import org.lewis.common.service.EmailTaskService;

import com.tocersoft.framework.core.annotations.Component;


@Component
public class EmailTaskServiceImpl implements EmailTaskService {

	public long addEmailTask(EmailTask emailTask) {
		String sql="insert into ts_email_task (type,content,status,createTime,sendTime,subject,receiver,planSendTime,sendType) values (?,?,?,?,?,?,?,?,?)";
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = QueryHelper.getConnection().prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
			ps.setObject(1, emailTask.getType());
			ps.setObject(2, emailTask.getContent());
			ps.setObject(3, emailTask.getStatus());
			ps.setObject(4, emailTask.getCreateTime());
			ps.setObject(5, emailTask.getSendTime());
			ps.setObject(6, emailTask.getSubject());
			ps.setObject(7, emailTask.getReceiver());
			ps.setObject(8, emailTask.getPlanSendTime());
			ps.setObject(9, emailTask.getSendType());
			ps.executeUpdate();
			rs = ps.getGeneratedKeys();
			return rs.next() ? rs.getLong(1) : -1;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtils.closeQuietly(rs);
			DbUtils.closeQuietly(ps);
		}
		return 0;
	}

	@Override
	public List<EmailTask> queryEmailTaskByStatus(String status, int start,int size) {
		String sql="select * from ts_email_task where status=?";
		return QueryHelper.queryPage(EmailTask.class, sql, start, size, status);
	}

	@Override
	public long updateEmailTaskStatusAndTime(Long taskId) {
		String sql="update ts_email_task set sendTime=?,status='"+EmailTask.STATUS.send+"' where id=?";
		return QueryHelper.update(sql,new Date(),taskId);
		
	}

}
